/**
 * function used to be called
 * @param info
 */
function fictionAddShowPostFictionInfo(info) {
    var parent = $('#post-fiction-result');
    info = '<li>' + info + '</li>';
    parent.append(info);
}


/**
 * 清除所有已经填写的内容
 */
function fictionAbandonClick() {
    $('#fiction-title').val('');
    $('#fiction-description').val('');
    $('#fiction-author').val('');
    $('#fiction-finish-year').val('');
}

/**
 * 检测内容，如果内容符合，则提交新的文章
 */
function fictionAddOnFinishFictionClick() {
    var titleHandle = $('#fiction-title');
    var title = titleHandle.val();

    var descriptionHandle = $('#fiction-description');
    var description = descriptionHandle.val();

    var rootCatlogHandle = $('#catlog-selection');
    var rootCatlog = rootCatlogHandle.val();

    var catlogHandle = $('#subcatlog-selection');
    var catlog = catlogHandle.val();

    var authorHandle = $('#fiction-author');
    var author = authorHandle.val();

    var finishYearHandle = $('#fiction-finish-year');
    var finishYear = finishYearHandle.val();

    var finished = $('#fiction-finished-checkbox').is(':checked');

    var token = getCookie("token");

    if (token == null ) {
        fictionAddShowPostFictionInfo('<strong>' + title + '</strong>' + '提交失败！' + '原因：未找到用户身份证明');
        return;
    }

    if (title == '') {
        fictionAddShowPostFictionInfo('<strong>題目不能為空</strong>');
        return;
    }

    if (description == '') {
        fictionAddShowPostFictionInfo('<strong>內容不能為空</strong>');
        return;
    }

    if (finished && finishYear == '') {
        fictionAddShowPostFictionInfo('<strong>完本年代不能為空</strong>');
        return;
    }

    if (finished && finishYear.length != 4) {
        fictionAddShowPostFictionInfo('<strong>完本年代必須是4個字長度</strong>');
        return;
    }

    if (finished && !isAllDigit(finishYear)) {
        fictionAddShowPostFictionInfo('<strong>完本年代必須是4個數字</strong>');
        return;
    }

    $.ajax(
        {
            type: 'post',
            async: true,
            data: {
                'title': title,
                'description': description,
                'rootcatlog': rootCatlog,
                'catlog': catlog,
                'author': author,
                'finishyear': finishYear,
                'finished': finished
            },
            url: document.location.origin + '/api/createfiction',
            dataType:'text',
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    fictionAddShowPostFictionInfo('<strong>' + title + '</strong>' + '提交成功！' + ' ' + json.createtime);
                    //clear all input
                    titleHandle.val('');
                    descriptionHandle.val('');
                    finishYearHandle.val('');
                }
                else {
                    fictionAddShowPostFictionInfo('<strong>' + title + '</strong>' + '提交失败！' + '原因：' + json.description  + ' ' + json.createtime);
                }
            },
            error: function () {
                console.log("Ajax 发生错误！");
            }
        }
    );
}

function fictionAddOnFastAddAuthorNameClick() {
    var handle = $('#author-name-fast');
    var author = handle.val();

    var info;
    if (author == null || author == '') {
        info = "作者名不能为空";
        fictionAddShowPostFictionInfo(info);
        return;
    }

    $.ajax(
        {
            type: 'post',
            async: true,
            data: {
                'author': author,
            },
            url: document.location.origin + '/api/addauthor',
            dataType:'text',
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    $('#fiction-author').val(author);
                    fictionAddShowPostFictionInfo("快速添加作者：<strong>" + author + "</strong> 成功");
                    handle.val('');
                }
                else {
                    fictionAddShowPostFictionInfo(json.description);
                }
            },
            error: function () {
                console.log("Ajax 发生错误！");
            }
        }
    );
}

function fictionAddOnCatlogSelectionClick() {
    var value = $('#catlog-selection').val();

    $.ajax(
        {
            type: 'post',
            async: true,
            data: {'rootcatlog': value},
            url: document.location.origin + '/api/getcatlogs',
            dataType:'text',
            success: function(data) {
                var json = JSON.parse(data);

                if (json.result == 200) {
                    var parent = $('#subcatlog-selection');
                    // remove original
                    // parent.children().slice(N).detach();
                    parent.children().slice(1).remove();

                    for (var i = 0; i < json.data.length; ++i) {
                        parent.append("<option>" + json.data[i] + "</option>");
                    }
                }
                else {
                    handle.css('display', 'block');
                    handle.text(data);
                }
            },
            error: function () {
                console.log("Ajax 发生错误！");
            }
        }
    );
}

/**
 * document ready
 */
$(document).ready(function() {
    // Instantiate the Bloodhound suggestion engine
    var authors = new Bloodhound({
        datumTokenizer: function(datum) {
            return Bloodhound.tokenizers.whitespace(datum.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            wildcard: '%QUERY',
            url: document.location.origin + '/api/getauthorlistjson?query=%QUERY',
            transform: function(response) {
                // Map the remote source JSON array to a JavaScript object array
                return $.map(response.data, function(data) {
                    return {
                        name: data
                    };
                });
            }
        }
    });

    // Instantiate the Typeahead UI
    $('#fiction-author').typeahead(null, {
        display: 'name',
        source: authors,
        limit: 1000, //如果这个不填，默认是搜索到的结果，也就是上面的transform.$.map返回结果的-1个
    });
});